<template>
  <div>
    <el-menu :default-active="activeIndex" mode="horizontal">
      <el-menu-item style="margin-left: 10%">
        <span class="logo">求知网</span>
      </el-menu-item>
      <el-menu-item index="1"><a href="/">首页</a></el-menu-item>
      <el-menu-item index="2">发现</el-menu-item>
      <el-menu-item index="3">关于</el-menu-item>
      <!-- 搜索框区域 -->
      <el-menu-item style="width: 30%; margin-left: 20px">
        <div>
          <el-input
            placeholder="请输入内容"
            v-model="topic_keyword"
            @keyup.enter.native="searchTopic(topic_keyword)"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchTopic(topic_keyword)"
            ></el-button>
          </el-input>
        </div>
      </el-menu-item>
      <!-- 头像区域 -->
      <el-menu-item style="margin-right: 16%; float: right">
        <!-- 判断是否登录 -->
        <div v-if="login">
          <div class="header_pic">
            <img :src="user_info.header_pic" />
            <a href="/user_info" style="margin-left: 15px">个人中心</a>
          </div>
        </div>
        <div class="btn" v-else>
          <el-button type="primary">
            <a href="/login" style="text-decoration: none">登陆</a>
          </el-button>
          <el-button type="success">
            <a href="/register" style="text-decoration: none">注册</a>
          </el-button>
        </div>
      </el-menu-item>
    </el-menu>
  </div>
</template>

<script>
export default {
  data () {
    return {
      activeIndex: '1',
      login: false,
      user_info: {},
      // 搜索的话题
      topic_keyword: ''
    }
  },
  created () {
    this.isLogin()
    this.watchRoute()
  },
  methods: {
    async isLogin () {
      if (JSON.parse(sessionStorage.getItem('user'))) {
        // 获取用户信息
        const { data } = await this.$http.get('/user_info?id=' + JSON.parse(sessionStorage.getItem('user')).user_id)
        this.user_info = data
        this.login = true
      } else {
        this.login = false
      }
    },
    searchTopic (topicKeyword) {
      if (topicKeyword === '') {
        this.$router.push('/')
        return this.$message.error('请输入搜索的内容!')
      } else {
        this.$router.push('/search?keyword=' + topicKeyword)
      }
    },
    watchRoute () {
      if (this.$route.path !== '/') {
        this.activeIndex = '0'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.block {
  width: 50px;
}

.header_pic {
  width: 40px;
  height: 40px;
  > img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}

.logo {
  color: #0066ff;
  font-size: 26px;
  margin-right: 10px;
}
</style>
